﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HPIT.RentHouse.Admin.App_Start
{
    using HPIT.RentHouse.Service.Entites;
    using log4net;
    using System.Linq;
    using System.Web.Mvc;

    public class LoggingActionFilter : ActionFilterAttribute
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(LoggingActionFilter));
        
        //全局变量
        // (controller的方法执行前)记录操作开始，带参数信息
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var actionName = filterContext.ActionDescriptor.ActionName;
            var parameters = filterContext.ActionParameters;

            // 记录参数信息
            var paramInfo = string.Join(", ", parameters.Select(p => $"{p.Key}: {p.Value}"));
            log.Info($"Executing action: {controllerName}/{actionName} with parameters: {paramInfo}");
          
                base.OnActionExecuting(filterContext);
        }

        //  (controller的方法执行后)记录操作结束，带执行结果信息
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var actionName = filterContext.ActionDescriptor.ActionName;

            // 检查是否有异常
            if (filterContext.Exception != null)
            {
                log.Error($"Action {controllerName}/{actionName} threw an exception", filterContext.Exception);
            }
            else
            {
                // 获取执行结果
                var result = filterContext.Result as JsonResult;
                if (result != null)
                {
                    log.Info($"Action {controllerName}/{actionName} executed successfully with result: {result.Data}");
                }
                else
                {
                    log.Info($"Action {controllerName}/{actionName} executed successfully.");
                }
            }

            base.OnActionExecuted(filterContext);
        }
    }
}
